﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Threading;
using Microsoft.SharePoint;
using IKEA.FileExchange.Domain;
using Microsoft.SharePoint.Utilities;
using System.Text;
using System.Collections.Generic;
using IKEA.FileExchange.Domain.FileCleanupManagement;
using IKEA.FileExchange.Domain.Files;

public partial class iframe_FilesToUploadList : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetStubDataSourceToFilesRepeater();
            hfIsConfidential.Value = "false";
        }
        else
        {
            bool isConfidential = bool.Parse(hfIsConfidential.Value);
            AddNewFilesToStore(isConfidential);
        }
    }

    protected void AddNewFilesToStore(bool isConfidential)
    {
        CleanupRule cleanupRule = (CleanupRule) Enum.Parse(typeof(CleanupRule), hfFilesDeletionDate.Value);

        DateTime dtDeletionDate = DateTime.Now;

        if (cleanupRule == CleanupRule.Month)
        {
            dtDeletionDate = dtDeletionDate.AddMonths(1);
        }
        else
        {
            dtDeletionDate = dtDeletionDate.AddDays(7);
        }

        StringBuilder errors = new StringBuilder();

        List<Guid> uploadedFilesIdents = new List<Guid>();
        
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
                {
                    SPContentTypeId fileContentTypeId = new SPContentTypeId(
                        isConfidential ? Constants.CT_IKEA_CONFIDENTIAL : Constants.CT_IKEADOCUMENT);

                    SPContentType fileContentType = spWeb.ContentTypes[fileContentTypeId];
                    SPFolder spTargetFolder = null;

                    if (isConfidential)
                    {
                        SPDocumentLibrary confidentialFileStore = IKEAFileStoreHelper.GetConfidentialFileStore(spWeb);
                        spTargetFolder = confidentialFileStore.RootFolder.SubFolders.Add(Guid.NewGuid().ToString());

                        spTargetFolder.Update();
                    }
                    else
                    {
                        SPDocumentLibrary publicFileStore = IKEAFileStoreHelper.GetPublicFileStore(spWeb);

                        string targetFolderPath = hfTargetFolder.Value;

                        if (!string.IsNullOrEmpty(targetFolderPath))
                        {
                            spTargetFolder = spWeb.GetFolder(targetFolderPath);
                        }
                        else
                        {
                            spTargetFolder = publicFileStore.RootFolder;
                        }
                        
                    }

                    foreach (RepeaterItem repFileItem in repFiles.Items)
                    {
                        FileUpload fileUpload = (FileUpload)repFileItem.FindControl("fileUpload");

                        if (fileUpload.HasFile)
                        {
                            SPFile file = null;

                            try
                            {
                                file = spTargetFolder.Files.Add(fileUpload.FileName, fileUpload.FileBytes);

                                file.Item["Title"] = fileUpload.FileName;
                                file.Item["ContentTypeId"] = fileContentType.Id;
                                file.Item[FileFieldNames.FileDeletionDate] = dtDeletionDate;

                                file.Update();
                                file.Item.Update();

                                uploadedFilesIdents.Add(file.Item.UniqueId);
                            }
                            catch (Exception e)
                            {
                                errors.AppendLine(e.Message);
                            }
                        }
                    }
                }
            }
        }
        );

        hfErrors.Value = errors.ToString();

        List<string> uploadedFilesIdentsStr = new List<string>();

        uploadedFilesIdentsStr = uploadedFilesIdents.ConvertAll<string>(delegate(Guid ident)
        {
            return ident.ToString();
        }
        );

        string[] identsArray = uploadedFilesIdentsStr.ToArray();

        hfUploadedFilesIdents.Value = string.Join(";", identsArray);
    }

    private void SetStubDataSourceToFilesRepeater()
    {
        int[] stubDataSource = new int[50];

        repFiles.DataSource = stubDataSource;
        repFiles.DataBind();
    }

    protected override void OnPreRender(EventArgs e)
    {
        

        base.OnPreRender(e);
    }
}
